$(function () {
    window.startDate = $('#datePicker').find('.start').html();
    var loading = $('#loading');
    var today = $('#doc').data('today');
    var customDate = new Date().customDays(-180);
    var halfYears = customDate.getFullYear()+'-'+(customDate.getMonth()+1)+'-'+customDate.getDate();
    var toggleLoading = function (isShow) {
        if (isShow) {
            loading.removeClass('hidden');
        } else {
            loading.addClass('hidden');
        }
    };

    var tip = function (obj, info) {
        obj.tip({
            content: info,
            background: "#000",
            color: "#fff"
        });
    };
    var refreshLayout = function (datas) {
        var totaCustomers = datas.totaCustomer;
        var guest = $('.guest-num').html(totaCustomers);
        var customerInfos = datas.item;
        if (customerInfos.length === 0) {
            $('#customerListBody').html('');
            $('#customerListBodyEmpty').removeClass('hidden');
            $('#customerListPage').addClass('hidden');
        } else {
            $('#customerListBodyEmpty').addClass('hidden');
            var templateHTML = $($('#templateCustomer').clone().html());
            var customerHTML = '';
            $.each(customerInfos, function (key, customerInfo) {
                templateHTML.find('.customer-name').html(customerInfo.name);
                if(customerInfo.mobile){
                    templateHTML.find('.customer-mobile').html('+'+customerInfo.areaCode+'&nbsp;'+customerInfo.mobile);
                }
                templateHTML.find('.customer-identity').html(customerInfo.identity?customerInfo.identity:'');
                templateHTML.find('.checkIn-time').html(customerInfo.startDate);
                templateHTML.find('.checkIn-duration').html(customerInfo.hour?customerInfo.hour:customerInfo.night);
                templateHTML.find('.customer-time').html(customerInfo.checkin);
                //templateHTML.find('.customer-total').html((parseFloat(customerInfo.receipt)+parseFloat(customerInfo.deposit)).toFixed(2));
                templateHTML.find('.customer-total').html(parseFloat(customerInfo.receipt).toFixed(2));
                templateHTML.find('.customer-details').attr('data-orderUser',customerInfo.orderUserId)
                
                customerHTML += templateHTML.prop('outerHTML');
            });
            $('#customerListBody').html(customerHTML);
            $('[data-toggle="tooltip"]').tooltip();
            var pageInfo = datas.page;
            var currentPage = parseInt(pageInfo.currentPage);
            var pages = parseInt(pageInfo.total);
            var pageContainer = $('#customerListPage');
            pageContainer.removeClass('hidden');
            var pageHTML = '';
            var templatePage = $($('#templatePage').clone().html());
            for (var i = 1; i <= pages; i++) {
                if (currentPage === i) {
                    templatePage.addClass('active');
                } else {
                    templatePage.removeClass('active');
                }
                templatePage.find('a').html(i).attr('data-value', i);
                pageHTML += templatePage.prop('outerHTML');
            }
            pageContainer.find('.pagination').html(pageHTML);
            pageContainer.find('.page-count').html(pages);
            pageContainer.find('.page-total').html(pageInfo.totalCount);
        }
    };

    var requestInfo = function (page, mobile, submitBtn) {
        window.lastRequestMobile = mobile;
        toggleLoading(true);
        var params = {
            'hotel': window.currentHotel,
            'currentPage': page,
        };
        if (mobile !== '') {
            params.keys = mobile;
        }
        params.startDate = $('#datePicker .start').text();
        params.endDate = $('#datePicker .end').text();
        ajaxRequest('/Home/Customer/customer', params, 'post', function (data, obj) {
            toggleLoading(false);
            window.serverDatas = data.data;
            refreshLayout(window.serverDatas);
        }, function (error, obj) {
            toggleLoading(false);
            if (typeof error.responseJSON == 'undefined') {
                tooltipWrong(obj, lang('tip.server'),1);
                return;
            }

            tooltipWrong(obj, error.responseJSON.info,1);
        }, submitBtn);
    };

    requestInfo(1, '', $('#filterSearch'));

    window.filterMobile = '';
    $('#customerListPage .pagination').on('click', 'li:not(.active) a', function () {
        var pageIndex = $(this).data('value');
        var submitBtn = $('#filterSearch');
        requestInfo(pageIndex, window.filterMobile, $('#filterSearch'));
    });

    $('#filterSearch').on('click', function(e) {
        e.preventDefault();
        var filterMobile = $('#filterMobile').val().trim();
        var submitBtn = $(this);
        if (filterMobile !== '' && !window.commonRegexp.mobile.test(filterMobile)) {
            tooltipWrong($('#filterMobile'), lang('tip.mobile'),1);
            return;
        }
        window.filterMobile = filterMobile;
        requestInfo(1, filterMobile, submitBtn);
    });
    // 选择日期
    var format = 'YYYY-MM-DD';
    $('#datePickerInput').daterangepicker({
        'showDropdowns': true,
        'autoApply': true,
        'dateLimit': {
            'days': 30
        },
        'locale': {
            'format': format,
            'applyLabel': lang('date.ensure'),
            'cancelLabel': lang('date.cancel'),
            'daysOfWeek': [
                lang('week.7'),
                lang('week.1'),
                lang('week.2'),
                lang('week.3'),
                lang('week.4'),
                lang('week.5'),
                lang('week.6')
            ],
            'monthNames': [
                lang('month.1'),
                lang('month.2'),
                lang('month.3'),
                lang('month.4'),
                lang('month.5'),
                lang('month.6'),
                lang('month.7'),
                lang('month.8'),
                lang('month.9'),
                lang('month.10'),
                lang('month.11'),
                lang('month.12')
            ],
            'firstDay': 1
        },
        'linkedCalendars': false,
        'parentEl': 'body',
        'startDate': window.startDate,
        'endDate': $('#datePicker').find('.end').html(),
        'minDate': '2000-01-01',
        'maxDate': '2038-01-01',
    }, function (start, end, label) {
        window.startDate = start.format(format);
        $('#datePicker').find('.start').html(window.startDate);
        $('#datePicker').find('.end').html(end.format(format));
    });
    
    
    $('#datePicker').on('click', function () {
        $('#datePickerInput').trigger('focus');
    });  
    $('#dpd1').val(halfYears);
    $('#dpd2').val(today);
    $('#dpd1').fdatepicker({
        format: 'yyyy-mm-dd',
        startDate: halfYears,
        endDate: today,
    });
    $('#dpd2').fdatepicker({
        format: 'yyyy-mm-dd',
        startDate: halfYears,
        endDate: today,
    });    
    var leadingOut = $('.leading-out');
    $('#derivedCheckout').on('click',function(){
        var btn = $(this);
        if(btn.attr('checked')){
            btn.removeAttr('checked'); 
            leadingOut.removeClass('submitForm');
        }else{
            btn.attr('checked',true);
            leadingOut.addClass('submitForm');
        }
    });
    $('.leading-out').on('click',function(){
        var btn = $(this);
        var startDate = $('#dpd1').val();
        var endDate = $('#dpd2').val();
        if(btn.hasClass('submitForm')){
            window.location.href ="/Home/Customer/exportCustomerList?hotel="+window.currentHotel+"&startDate="+startDate+"&endDate="+endDate;
            $('#derivedFormModal').modal('hide');
        }
    });

    //身份认证
    var authenticationModal = $('#authenticationModal');
    authenticationModal.on('click',function(e){
        e.stopPropagation();
        authenticationModal.hide();
    }).on('click','.modal-content',function(e){
        e.stopPropagation();
        authenticationModal.show();
    }); 
    $('#customerListBody').on('click','.customer-details',function(){
        var btn = $(this);
        var orderUser = btn.data('orderuser');
        var param = {};
        param.hotel = window.currentHotel;
        param.orderUser = orderUser;
        ajaxRequest('/Home/Order/getOrderUserInfo', param, 'post', function(data) {
            var info = data.data;
            authenticationModal.find('.userName').text(info.name);
            authenticationModal.find('.userIdCard').text(info.identity);
            authenticationModal.find('.user-tip-Name').text(info.name);
            authenticationModal.find('.user-tip-idcard').text(info.identity);
            authenticationModal.find('.user-tip-nation').text(info.idnation);
            authenticationModal.find('.user-tip-address').text(info.idaddress);
            if(parseInt(info.idsex) == 1){
                authenticationModal.find('.user-tip-gender').text(lang('male'));
            }else if(parseInt(info.idsex) == 0){
                authenticationModal.find('.user-tip-gender').text(lang('female'));
            }else{
                authenticationModal.find('.user-tip-gender').text('');
            }
            authenticationModal.show();
        }, function(error) {

        }); 
        authenticationModal.show();
    });   
})